<template>
    <div class="ai-chat-container">
      <a-card class="chat-card">
        <!-- 聊天标题 -->
        <div class="chat-header">
          <div class="header-left">
            <h2>AI 智能助手</h2>
            <span class="message-count">
              (共 {{ chatMessages.length }} 条对话)
            </span>
          </div>
          <a-button type="primary" @click="clearChat" danger>
            <delete-outlined />
            清空对话
          </a-button>
        </div>
  
        <!-- 聊天记录区域 -->
        <div class="chat-messages" ref="messageContainer">
          <div v-for="(message, index) in chatMessages" :key="index" 
               :class="['message-item', message.type === 'user' ? 'user-message' : 'ai-message']">
            <div class="message-avatar">
              <a-avatar :size="40">
                {{ message.type === 'user' ? username : 'AI' }}
              </a-avatar>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(message.content)"></div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>
  
        <!-- 输入区域 -->
        <div class="chat-input">
          <a-textarea
            v-model:value="userInput"
            :rows="3"
            placeholder="请输入您的问题..."
            :disabled="loading"
            @keypress.enter.prevent="handleSend"
          />
          <div class="input-actions">
            <a-button 
              type="primary" 
              :loading="loading"
              @click="handleSend"
              :disabled="!userInput.trim()"
            >
              <send-outlined />
              发送
            </a-button>
          </div>
        </div>
      </a-card>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick, watch } from 'vue'
  import { message, Modal } from 'ant-design-vue'
  import { DeleteOutlined, SendOutlined } from '@ant-design/icons-vue'
  import { chat } from '@/api/ai'
  import dayjs from 'dayjs'
  import MarkdownIt from 'markdown-it'
  const username=JSON.parse(localStorage.getItem('admin')).loginName
  const adminId=JSON.parse(localStorage.getItem("admin")).adminId
  const md = new MarkdownIt()
  // 聊天记录
  const chatMessages = ref([
    {
      type: 'ai',
      content: '你好！我是AI助手，很高兴为您服务。请问有什么我可以帮您的吗？',
      timestamp: new Date()
    }
  ])
  
  const userInput = ref('')
  const loading = ref(false)
  const messageContainer = ref(null)

  // 添加这些函数来处理历史记录
  const CHAT_HISTORY_KEY = `ai_chat_history_${adminId}`

  // 从 localStorage 加载历史记录
  const loadChatHistory = () => {
    try {
      const savedHistory = localStorage.getItem(CHAT_HISTORY_KEY)
      if (savedHistory) {
        const history = JSON.parse(savedHistory)
        // 转换时间戳回 Date 对象
        chatMessages.value = history.map(msg => ({
          ...msg,
          timestamp: new Date(msg.timestamp)
        }))
      }
    } catch (error) {
      console.error('加载历史记录失败:', error)
      message.error('加载历史记录失败')
    }
  }

  // 保存历史记录到 localStorage
  const saveChatHistory = () => {
    try {
      localStorage.setItem(CHAT_HISTORY_KEY, JSON.stringify(chatMessages.value))
    } catch (error) {
      console.error('保存历史记录失败:', error)
      message.error('保存历史记录失败')
    }
  }

  // 发送消息
  const handleSend = async () => {
    if (!userInput.value.trim() || loading.value) return
  
    console.log('发送消息:', userInput.value)
    const userMessage = userInput.value
    loading.value = true

    // 添加用户消息
    chatMessages.value.push({
      type: 'user',
      content: userMessage,
      timestamp: new Date()
    })

    // 添加临时的 AI 响应消息
    chatMessages.value.push({
      type: 'ai',
      content: '正在思考中...',
      timestamp: new Date()
    })

    // 保存当前状态
    saveChatHistory()
    
    try {
      console.log('调用 API...')
      const response = await chat(
        {
            message: userMessage
        }
      )
      console.log('API 响应:', response)
      
      if (response.code === 200) {
        chatMessages.value[chatMessages.value.length-1]={
          type: 'ai',
          content: response.data,
          timestamp: new Date()
        }
        // 保存更新后的状态
        saveChatHistory()
      } else {
        chatMessages.value.pop()
        message.error(response.msg || '发送消息失败')
      }
    } catch (error) {
      console.error('发送消息失败:', error)
      chatMessages.value.pop()
      message.error('发送消息失败，请重试')
    } finally {
      loading.value = false
      userInput.value = ''
    }
  }
  
  // 清空对话
  const clearChat = () => {
    chatMessages.value = [{
      type: 'ai',
      content: '你好！我是AI助手，很高兴为您服务。请问有什么我可以帮您的吗？',
      timestamp: new Date()
    }]
    // 保存清空后的状态
    saveChatHistory()
  }
  
  // 格式化消息内容（支持Markdown）
  const formatMessage = (content) => {
    return md.render(content)
  }
  
  // 格式化时间
  const formatTime = (timestamp) => {
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
  }
  
  // 监听消息变化，自动滚动到底部
  watch(chatMessages, () => {
    nextTick(() => {
      if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight
      }
    })
  })
  
  // 组件挂载时滚动到底部
  onMounted(() => {
    loadChatHistory()
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  })
  </script>
  
  <style scoped>
  .ai-chat-container {
    padding: 24px;
    height: 100vh;
    background-color: #f0f2f5;
  }
  
  .chat-card {
    height: calc(100vh - 48px);
    display: flex;
    flex-direction: column;
  }
  
  .chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .chat-header h2 {
    margin: 0;
    color: #1f1f1f;
  }
  
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px 0;
  }
  
  .message-item {
    display: flex;
    margin-bottom: 20px;
    gap: 12px;
  }
  
  .user-message {
    flex-direction: row-reverse;
  }
  
  .message-content {
    max-width: 70%;
  }
  
  .user-message .message-content {
    text-align: right;
  }
  
  .message-text {
    padding: 12px 16px;
    border-radius: 8px;
    background-color: #f0f0f0;
    word-break: break-word;
  }
  
  .user-message .message-text {
    background-color: #1890ff;
    color: white;
  }
  
  .message-time {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }
  
  .chat-input {
    margin-top: 20px;
    border-top: 1px solid #f0f0f0;
    padding-top: 20px;
  }
  
  .input-actions {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
  
  /* Markdown 样式 */
  :deep(.message-text) {
    line-height: 1.6;
  }
  
  :deep(.message-text pre) {
    background-color: #f6f8fa;
    padding: 12px;
    border-radius: 6px;
    overflow-x: auto;
  }
  
  :deep(.message-text code) {
    font-family: 'Courier New', Courier, monospace;
  }
  
  :deep(.user-message .message-text pre) {
    background-color: rgba(255, 255, 255, 0.1);
  }
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .message-count {
    color: #999;
    font-size: 14px;
  }
  </style>